#include <getopt.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "oraygpio.h"
#include "hisi-gpio.h"
#include "ctrl_misc_led.h"

enum IOFLG {
	io_flag_null = 0,
	io_flag_in = 1,
	io_flag_out_high = 2,
	io_flag_out_low = 3,
};
//测试 iocfg地址用
extern "C" uint32_t get_io_cfg_addr(int regindex, const char *name);

int io_flag = 0;
int gpio_group_id = -1;
int gpio_num_id = -1;
int muxctrl_reg = -1;
uint32_t muxctrl_val = 0xffffffff;

void print_die_id(void)
{
	uint32_t dat[6];
	Get_die_id((unsigned char *)dat, 24);

	for (int i = 0; i < 6; i++) {
		printf("%#x\n", dat[i]);
	}
}

int gpio_switch(int c)
{
	switch (c) {
	//oraygpio -I -G 2 -N 1,读取gpio2_1
	case 'I':
		io_flag = io_flag_in;
		return 0;
	case 'H':
		io_flag = io_flag_out_high;
		return 0;
	case 'L':
		io_flag = io_flag_out_low;
		return 0;
	case 'G':
		gpio_group_id = atoi(optarg);
		return 0;
	case 'N':
		gpio_num_id = atoi(optarg);
		return 0;
	case 'D':
		print_die_id();
		exit(0);
	case 'S': {
		uint32_t tmpval;
		//正则
		//匹配0x123和0X123
		if (sscanf(optarg, "0%*[xX]%x", &tmpval) == 1) {
			muxctrl_val = tmpval;
		} else if (sscanf(optarg, "%d", &tmpval) == 1) {
			muxctrl_val = tmpval;
		}
		return 0;
	}
	//测试 iocfg地址用
	case 'T': {
		int num = atoi(optarg);
		uint32_t addr = get_io_cfg_addr(num, DEVICE);
		printf("addr = %#X\n", addr);
		exit(0);
	}
	case 'M':
		muxctrl_reg = atoi(optarg);
		return 0;
	}
	return -1;
}

int gpio_sp()
{
	int succflg = 0;
	if (muxctrl_val != 0xffffffff && muxctrl_reg != -1) {
		printf("mux reg %d , val 0x%x\n", muxctrl_reg, muxctrl_val);
		hisi_gpio_n_muxctrl_config(muxctrl_reg, muxctrl_val);
		succflg++;
	}

	if (io_flag != 0 && gpio_group_id != -1 && gpio_num_id != -1) {
		printf("io_flag %d,gpio_group_id %d gpio_num_id %d,", io_flag, gpio_group_id, gpio_num_id);
		if (io_flag == io_flag_in) {
			int val = hisi_gpio_get_pin(gpio_group_id, gpio_num_id);
			printf("get %d", val);
			succflg++;
		} else if (io_flag == io_flag_out_high || io_flag == io_flag_out_low) {
			hisi_gpio_set_pin_val(gpio_group_id, gpio_num_id, io_flag == io_flag_out_high ? 1 : 0);
			printf("set %d\n", io_flag == io_flag_out_high ? 1 : 0);
			succflg++;
		}
		printf("\n");
	}

	return succflg;
}
